package example.controller;

import example.dao.UserDao;
import example.model.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {

    UserDao userDao = new UserDao();


    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        req.setCharacterEncoding("utf-8");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        try {
//            验证用户是否存在---替换具体的逻辑
            User user = userDao.getUserByUserNameAndPassword(username,password);
            if(user!=null){
                req.getSession().setAttribute("user",user);
//                这里可以是主页
                resp.sendRedirect("/");
            }else{
                req.getSession().setAttribute("msg","用户名或密码错误");
                resp.sendRedirect("/msg.jsp");
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.sendRedirect("/login.jsp");
    }
}
